﻿using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;

namespace SPDB.BTAP.Infrastructure.Data.DapperCore
{
    class DataMapping<TModel> where TModel : class
    {
        #region 数据库类型+DataBaseType
        /// <summary>
        /// 数据库类型
        /// </summary>
        public static string DataBaseType
        {
            get
            {
                string strType = "";//ConfigurationManager.AppSettings["DataBaseType"];
                if (!string.IsNullOrEmpty(strType))
                {
                    return strType;
                }
                else
                {
                    return string.Empty;
                }
            }
        }
        #endregion

        #region 主键属性字段+PrimaryKey
        /// <summary>
        /// 主键字段名称
        /// </summary>
        public static string PrimaryKey
        {
            get
            {
                Type t = typeof(TModel);
                TableInfoAttribute tableInfo = t.GetCustomAttribute(typeof(TableInfoAttribute), true) as TableInfoAttribute;
                if (tableInfo != null)//如果没有标识表信息特性，则通过表名向数据库中得到主键信息
                {
                    return tableInfo.PrimaryKey;
                }
                else
                {
                    string tableName = TableName();
                    string result = Convert.ToString(DataBaseAccess.ExecuteScalar(string.Format(@"with Temp as(SELECT name FROM SysColumns WHERE id=Object_Id('{0}') and colid in (select top 10 colid from sysindexkeys where id=Object_Id('{0}') and indid=1)) select stuff((SELECT ','+name from Temp FOR xml path('')),1,1,'')", tableName)));
                    return result;
                }
            }
        }
        #endregion

        #region 获取表名+TableName
        /// <summary>
        /// 获取表名
        /// </summary>
        /// <param name="prev">数据库表名前缀</param>
        /// <returns></returns>
        public static string TableName(string prev = "")
        {
            Type t = typeof(TModel);
            TableInfoAttribute tableInfo = t.GetCustomAttribute(typeof(TableInfoAttribute), true) as TableInfoAttribute;
            return tableInfo != null ? tableInfo.TableName : string.Concat(prev, t.Name);
        }
        #endregion

        #region Select 查询语句+GetQuerySql
        /// <summary>
        /// Select 查询语句
        /// </summary>
        /// <returns></returns>
        public static string GetQuerySql()
        {
            StringBuilder sql = new StringBuilder("select * from ");
            sql.Append(TableName());

            return sql.ToString();
        }
        #endregion

        #region Select 查询语句+GetQuerySql
        /// <summary>
        /// Select 查询语句
        /// </summary>
        /// <returns></returns>
        public static string GetQuerySqlWithKeys()
        {
            StringBuilder sql = new StringBuilder("select * from ");
            sql.Append(TableName());
            sql.Append(GetWhereSql());
            
            return sql.ToString();
        }
        #endregion

        #region Insert非Null属性的对象实例 Sql 语句+GetInsertSql
        /// <summary>
        /// Insert 非Null属性的对象实例 Sql 语句
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public static string GetInsertSql(TModel model)
        {
            StringBuilder sql = new StringBuilder("insert into ");

            string[] props = Propertys(model);
            sql.Append(TableName());
            sql.Append("(");
            sql.Append(string.Join(",", props));
            sql.Append(") values(@");
            sql.Append(string.Join(",@", props));
            sql.Append(");select @@ROWCOUNT");

            return sql.ToString();
        }
        #endregion


        #region Insert非Null属性的对象实例 Sql 语句+GetInsertSql
        /// <summary>
        /// Insert 非Null属性的对象实例 Sql 语句
        /// </summary>
        /// <param name="model"></param>
        /// <param name="identityKey">主键是否是自增长主键</param>
        /// <returns></returns>
        public static string GetInsertSql(TModel model, bool identityKey)
        {
            StringBuilder sql = new StringBuilder("insert into ");

            if (identityKey)
            {
                string[] props = Propertys(model);
                sql.Append(TableName());
                sql.Append("(");
                sql.Append(string.Join(",", props));
                sql.Append(") values(@");
                sql.Append(string.Join(",@", props));
                sql.Append(");select @@IDENTITY");
            }
            else
            {
                string[] props = Propertys(model);
                sql.Append(TableName());
                sql.Append("(");
                sql.Append(string.Join(",", props));
                sql.Append(") values(@");
                sql.Append(string.Join(",@", props));
                sql.Append(");");
            }

            return sql.ToString();
        }
        #endregion

        #region Delete Sql 语句+GetDeleteSql
        /// <summary>
        /// Delete Sql 语句
        /// </summary>
        /// <returns></returns>
        public static string GetDeleteSql()
        {
            if (PrimaryKey.Contains(","))
            {
                throw new Exception("GetDeleteSqlSingle()不能处理组合主键的情况");
            }
            return string.Format(@"delete from {0} where {1} in @IdList", TableName(), PrimaryKey);
        }
        #endregion

        #region Delete Sql 语句+GetDeleteSql
        /// <summary>
        /// Delete Sql 语句
        /// </summary>
        /// <returns></returns>
        public static string GetDeleteSqlSingle()
        {
            if (PrimaryKey.Contains(","))
            {
                throw new Exception("GetDeleteSqlSingle()不能处理组合主键的情况");
            }
            return string.Format(@"delete from {0} where {1} = @PrimaryKey", TableName(), PrimaryKey);
        }
        #endregion

        #region Delete Sql 语句+GetDeleteSql
        /// <summary>
        /// Delete Sql 语句
        /// </summary>
        /// <returns></returns>
        public static string GetDeleteSqlSingle(TModel model)
        {
            return string.Format(@"delete from {0}{1}", TableName(), GetWhereSql());
        }
        #endregion

        #region Update 非Null属性的对象实例 Sql语句+GetUpdateSql
        /// <summary>
        /// Update 非Null属性的对象实例 Sql语句
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public static string GetUpdateSql(TModel model)
        {
            StringBuilder sql = new StringBuilder("update ");
            string[] props = Propertys(model);
            sql.Append(TableName());
            sql.Append(" set ");
            foreach (string propName in props)
            {
                sql.Append(propName + "=@" + propName + ",");
            }
            sql.Remove(sql.Length - 1, 1);
            sql.Append(GetWhereSql());
            return sql.ToString();
        }
        #endregion

        #region 主键且非Null属性集合+Propertys
        /// <summary>
        /// 非主键且非Null属性
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public static string[] Propertys(TModel model)
        {
            PropertyInfo[] props = typeof(TModel).GetProperties();
            List<string> list = new List<string>();
            if (props != null && props.Length > 0)
            {
                foreach (PropertyInfo prop in props)
                {
                    if (prop.GetValue(model, null) != null)
                    {
                        if (prop.SetMethod.IsVirtual)
                            continue;
                        if (!AttributeExtend.IsWriteable(prop))
                            continue;

                        list.Add(prop.Name);
                    }
                }
            }

            return list.ToArray();
        }
        #endregion

        private static string GetWhereSql()
        {
            StringBuilder sqlWhere = null;
            string primaryKey = PrimaryKey;

            if (string.IsNullOrEmpty(primaryKey))
                throw new Exception(TableName() + "表的主键不存在");

            string[] keys = primaryKey.Split(',');
            foreach (string key in keys)
            {
                if (sqlWhere == null)
                    sqlWhere = new StringBuilder(string.Format(" where {0}=@{0}", key));
                else
                    sqlWhere.Append(string.Format(" and {0}=@{0}", key));
            }
            return sqlWhere.ToString();
        }
    }
}